package top.dancun.easbaseinfo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.dancun.common.utils.PageUtils;
import top.dancun.common.utils.Query;
import top.dancun.easbaseinfo.dao.DeptDao;
import top.dancun.easbaseinfo.entity.DeptEntity;
import top.dancun.easbaseinfo.service.DeptService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("deptService")
public class DeptServiceImpl extends ServiceImpl<DeptDao, DeptEntity> implements DeptService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DeptEntity> page = this.page(
                new Query<DeptEntity>().getPage(params),
                new QueryWrapper<DeptEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<DeptEntity> listDeptTree() {
        List<DeptEntity> depts = this.list();
        Map<Integer,DeptEntity> deprmap = new HashMap<>();
        depts.forEach(deptEntity -> {
            deprmap.put(deptEntity.getDeptId(),deptEntity);
        });
        depts = listToTree(deprmap,depts);
        return depts;
    }

    private List<DeptEntity> listToTree(Map<Integer,DeptEntity> deptmap ,List<DeptEntity> depts){
        depts = depts.stream().filter(dept->{
            DeptEntity parent = deptmap.get(dept.getParentId());
            if(Objects.nonNull(parent)){
                parent.getList().add(dept);
                return  false;
            }else {
                return true;
            }
        }).collect(Collectors.toList());

        return depts;
    }

}